package com.zh.webcommon.common.auth;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.zh.webcommon.HeaderConst.*;

/**
 * 填充当前登录用户信息
 * <br/>
 * 从Header中获取登录用户信息，并缓存到LoginUserHolder中
 * <br/>
 * 拦截器会拦截Controller的请求
 * @author ZH
 * @date 19:16 2021/12/4
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LoginUserFillInterceptor implements HandlerInterceptor {

    public LoginUserFillInterceptor() {
        log.info("[LoginUserInterceptor] constructor ...");
    }

    //方法前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //user值的格式user=101,xiao,[user]
        var userStr = request.getHeader(HEADER_USER_INFO);
        var tenantId = request.getHeader(HEADER_TENANT_ID);
        var userType = request.getHeader(HEADER_USER_TYPE);

//        var uuid = request.getHeader(HEADER_UUID);
//        log.debug("获取请求头Authorization={} ...", request.getHeader(HEADER_AUTH));
//        log.debug("获取请求头X-user={} ...", userStr);
//        log.debug("获取请求头X-tenantId={} ...", tenantId);
//        log.debug("获取请求头X-uuid={} ...", uuid);

        if (StringUtils.hasText(userStr)) {
            try {
                var plaintStr = new String(Base64.getDecoder().decode(userStr));
                retainLoginInfo(plaintStr);
            } catch (Exception ex) {
                log.error("请求头user的值解析为登录信息时发生错误，msg={}", ex.getMessage());
            }
        }

        if (StringUtils.hasText(userType)) {
            LoginUserHolder.putUserType(userType);
        }

        if (StringUtils.hasText(tenantId)) {
            LoginUserHolder.putTenantId(tenantId);
        }
        return true;
    }

    /**
     * 拥有登录信息
     *
     * @param value
     */
    private static void retainLoginInfo(String value) {
        Pattern pattern = Pattern.compile("\\[(.*)\\]");
        Matcher matcher = pattern.matcher(value);

        String[] split = value.split(",");
        var userId = split[0];
        var username = split[1];
        var roles = matcher.find() ? matcher.group(1) : "";

        log.debug("LoginUserHolder putUser [id={},username={},roles={} ]", userId, username, roles);
        LoginUserHolder.putUser(userId, username, roles);

    }

    // 所有interceptor执行完成后——>完成视图解析后——>回调执行此方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        LoginUserHolder.remove();
        log.debug("LoginUserHolder remove ... ");
    }
}
